<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit, Plus, Refresh, Search, Setting } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import {
  getBuildingController,
  getHouseController,
  getMeterCategoryController,
  getMeterRecordController,
  getOwnerController,
} from '@/api-client'
import type {
  Building,
  HouseVO,
  MeterCategory,
  MeterCategorySaveRequest,
  MeterRecordQueryRequest,
  MeterRecordSaveRequest,
  MeterRecordVO,
  OwnerVO,
} from '@/api-client'

interface MeterRecordFormModel {
  id?: number
  typeId?: number
  buildingId?: number
  houseId?: number
  previousReading?: number
  currentReading?: number
  previousTime?: string
  currentTime?: string
  checkTime?: string
  meter?: string
  remarks?: string
}

interface MeterCategoryFormModel {
  id?: number
  name: string
}

interface OwnerOption {
  id: number
  name: string
  tel?: string
  houseLabel?: string
}

const meterRecordApi = getMeterRecordController()
const meterCategoryApi = getMeterCategoryController()
const buildingApi = getBuildingController()
const houseApi = getHouseController()
const ownerApi = getOwnerController()

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<MeterRecordVO[]>([])
const total = ref(0)
const selectedRows = ref<MeterRecordVO[]>([])

const buildingOptions = ref<Building[]>([])
const searchHouseOptions = ref<HouseVO[]>([])
const formHouseOptions = ref<HouseVO[]>([])
const meterCategories = ref<MeterCategory[]>([])
const ownerOptions = ref<OwnerOption[]>([])
const ownerLoading = ref(false)

const houseCache = new Map<number, HouseVO[]>()

const pagination = reactive({
  current: 1,
  pageSize: 10,
})

const searchState = reactive({
  buildingId: undefined as number | undefined,
  currentRange: [] as string[] | [],
})

const searchForm = reactive<MeterRecordQueryRequest>({
  current: 1,
  pageSize: 10,
  typeId: undefined,
  houseId: undefined,
  ownerId: undefined,
  meter: '',
})

const createEmptyForm = (): MeterRecordFormModel => ({
  id: undefined,
  typeId: undefined,
  buildingId: undefined,
  houseId: undefined,
  previousReading: undefined,
  currentReading: undefined,
  previousTime: undefined,
  currentTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  checkTime: undefined,
  meter: '',
  remarks: '',
})

const meterForm = reactive<MeterRecordFormModel>(createEmptyForm())
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const isEdit = ref(false)

const rules = reactive<FormRules<MeterRecordFormModel>>({
  typeId: [{ required: true, message: '请选择抄表类型', trigger: 'change' }],
  buildingId: [{ required: true, message: '请选择所属楼栋', trigger: 'change' }],
  houseId: [{ required: true, message: '请选择房屋', trigger: 'change' }],
  currentReading: [{ required: true, message: '请输入本次读数', trigger: 'blur' }],
  currentTime: [{ required: true, message: '请选择本次抄表时间', trigger: 'change' }],
})

const typeDialogVisible = ref(false)
const typeLoading = ref(false)
const typeFormRef = ref<FormInstance>()
const typeForm = reactive<MeterCategoryFormModel>({ name: '' })
const typeRules = reactive<FormRules<MeterCategoryFormModel>>({
  name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
})
const editingTypeId = ref<number | undefined>()

const ownerLabel = (option: OwnerOption) => {
  const parts = [option.name]
  if (option.houseLabel) parts.push(option.houseLabel)
  if (option.tel) parts.push(option.tel)
  return parts.join(' / ')
}

const formatNumber = (value?: number) => {
  if (value === undefined || value === null) return '-'
  return Number(value).toFixed(2)
}

const fetchMeterCategories = async () => {
  try {
    const response = await meterCategoryApi.list2()
    if (response.code === 200) {
      meterCategories.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取抄表类型失败')
    }
  } catch (error) {
    console.error('fetchMeterCategories error:', error)
    ElMessage.error('获取抄表类型失败，请稍后重试')
  }
}

const fetchBuildingList = async () => {
  try {
    const response = await buildingApi.getAllBuildings()
    if (response.code === 200) {
      buildingOptions.value = response.data || []
    }
  } catch (error) {
    console.error('fetchBuildingList error:', error)
  }
}

const loadHousesByBuilding = async (buildingId: number) => {
  if (houseCache.has(buildingId)) {
    return [...(houseCache.get(buildingId) || [])]
  }
  try {
    const response = await houseApi.getHousesByBuildingId(buildingId)
    if (response.code === 200) {
      const list = response.data || []
      houseCache.set(buildingId, list)
      return [...list]
    }
  } catch (error) {
    console.error('loadHousesByBuilding error:', error)
  }
  return []
}

const fetchOwnerOptions = async (keyword = '') => {
  ownerLoading.value = true
  try {
    const response = await ownerApi.listOwner({
      current: 1,
      pageSize: 20,
      userName: keyword || undefined,
    })
    if (response.code === 200 && response.data) {
      ownerOptions.value = (response.data.records || []).map<OwnerOption>((item) => ({
        id: item.id!,
        name: item.userName || '未命名业主',
        tel: item.tel || undefined,
        houseLabel: item.houseVO
          ? `${item.houseVO.building?.numbers || ''} ${item.houseVO.numbers || ''}`
          : undefined,
      }))
    }
  } catch (error) {
    console.error('fetchOwnerOptions error:', error)
  } finally {
    ownerLoading.value = false
  }
}

const applySearchFilters = () => {
  if (searchState.currentRange.length === 2) {
    searchForm.currentTimeFrom = searchState.currentRange[0]
    searchForm.currentTimeTo = searchState.currentRange[1]
  } else {
    searchForm.currentTimeFrom = undefined
    searchForm.currentTimeTo = undefined
  }
}

const fetchMeterRecordList = async () => {
  loading.value = true
  applySearchFilters()
  try {
    const response = await meterRecordApi.search4({
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    })
    if (response.code === 200 && response.data) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取抄表记录失败')
    }
  } catch (error) {
    console.error('fetchMeterRecordList error:', error)
    ElMessage.error('获取抄表记录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  searchForm.current = 1
  fetchMeterRecordList()
}

const handleReset = () => {
  searchForm.typeId = undefined
  searchForm.houseId = undefined
  searchForm.ownerId = undefined
  searchForm.meter = ''
  searchState.buildingId = undefined
  searchState.currentRange = []
  searchHouseOptions.value = []
  handleSearch()
}

const handleSelectionChange = (rows: MeterRecordVO[]) => {
  selectedRows.value = rows
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchMeterRecordList()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchMeterRecordList()
}

const resetForm = () => {
  Object.assign(meterForm, createEmptyForm())
  formHouseOptions.value = []
  formRef.value?.clearValidate()
}

const openDialog = () => {
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
  submitLoading.value = false
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  openDialog()
}

const handleEdit = async (row: MeterRecordVO) => {
  isEdit.value = true
  resetForm()
  meterForm.id = row.id
  meterForm.typeId = row.typeId
  meterForm.houseId = row.houseId
  meterForm.previousReading = row.previousReading
  meterForm.currentReading = row.currentReading
  meterForm.previousTime = row.previousTime
  meterForm.currentTime = row.currentTime
  meterForm.checkTime = row.checkTime
  meterForm.meter = row.meter || ''
  meterForm.remarks = row.remarks || ''
  const buildingId = row.house?.building?.id
  if (buildingId) {
    meterForm.buildingId = buildingId
    const houses = await loadHousesByBuilding(buildingId)
    formHouseOptions.value = houses
  }
  openDialog()
}

const submitForm = async (form: FormInstance | undefined) => {
  if (!form) return
  await form.validate(async (valid) => {
    if (!valid) return
    if (!meterForm.typeId || !meterForm.houseId || meterForm.currentReading === undefined || !meterForm.currentTime) {
      return
    }
    if (
      meterForm.previousReading !== undefined &&
      meterForm.currentReading < meterForm.previousReading
    ) {
      ElMessage.warning('本次读数不能小于上次读数')
      return
    }
    if (
      meterForm.previousTime &&
      dayjs(meterForm.previousTime).isAfter(dayjs(meterForm.currentTime))
    ) {
      ElMessage.warning('本次抄表时间需晚于上次抄表时间')
      return
    }

    const payload: MeterRecordSaveRequest = {
      typeId: meterForm.typeId,
      houseId: meterForm.houseId,
      previousReading: meterForm.previousReading,
      currentReading: meterForm.currentReading,
      previousTime: meterForm.previousTime,
      currentTime: meterForm.currentTime,
      checkTime: meterForm.checkTime,
      meter: meterForm.meter,
      remarks: meterForm.remarks,
    }

    submitLoading.value = true
    try {
      if (isEdit.value && meterForm.id) {
        await meterRecordApi.update6(meterForm.id, payload)
        ElMessage.success('更新成功')
      } else {
        await meterRecordApi.add6(payload)
        ElMessage.success('新增成功')
      }
      closeDialog()
      fetchMeterRecordList()
    } catch (error) {
      console.error('submitForm error:', error)
      ElMessage.error(isEdit.value ? '更新失败，请稍后重试' : '新增失败，请稍后重试')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleDelete = async (row: MeterRecordVO) => {
  if (!row.id) return
  try {
    await ElMessageBox.confirm('确认删除该抄表记录吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    loading.value = true
    await meterRecordApi.delete6({ id: row.id })
    ElMessage.success('删除成功')
    fetchMeterRecordList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleDelete error:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const handleBatchDelete = async () => {
  const ids = selectedRows.value
    .map((item) => item.id)
    .filter((id): id is number => id !== undefined)
  if (ids.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  try {
    await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 条记录吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    loading.value = true
    await meterRecordApi.deleteBatch5(ids)
    ElMessage.success('批量删除成功')
    fetchMeterRecordList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleBatchDelete error:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const remoteSearchOwner = (keyword: string) => {
  fetchOwnerOptions(keyword)
}

const handleSearchBuildingChange = async (buildingId?: number) => {
  searchForm.houseId = undefined
  if (!buildingId) {
    searchHouseOptions.value = []
    return
  }
  const houses = await loadHousesByBuilding(buildingId)
  searchHouseOptions.value = houses
}

const handleFormBuildingChange = async (buildingId?: number) => {
  meterForm.houseId = undefined
  if (!buildingId) {
    formHouseOptions.value = []
    return
  }
  const houses = await loadHousesByBuilding(buildingId)
  formHouseOptions.value = houses
}

watch(
  () => searchState.buildingId,
  (value) => {
    handleSearchBuildingChange(value)
  }
)

watch(
  () => meterForm.buildingId,
  (value) => {
    handleFormBuildingChange(value)
  }
)

const openTypeDialog = () => {
  typeDialogVisible.value = true
  fetchMeterCategories()
  resetTypeForm()
}

const resetTypeForm = () => {
  editingTypeId.value = undefined
  Object.assign(typeForm, { name: '' })
  typeFormRef.value?.clearValidate()
}

const handleEditType = (type: MeterCategory) => {
  editingTypeId.value = type.id
  typeForm.name = type.name || ''
}

const submitTypeForm = async (form: FormInstance | undefined) => {
  if (!form) return
  await form.validate(async (valid) => {
    if (!valid) return
    const payload: MeterCategorySaveRequest = { name: typeForm.name }
    typeLoading.value = true
    try {
      if (editingTypeId.value) {
        await meterCategoryApi.update7(editingTypeId.value, payload)
        ElMessage.success('更新类型成功')
      } else {
        await meterCategoryApi.add7(payload)
        ElMessage.success('新增类型成功')
      }
      await fetchMeterCategories()
      resetTypeForm()
    } catch (error) {
      console.error('submitTypeForm error:', error)
      ElMessage.error('保存失败，请稍后重试')
    } finally {
      typeLoading.value = false
    }
  })
}

const handleDeleteType = async (type: MeterCategory) => {
  if (!type.id) return
  try {
    await ElMessageBox.confirm(`确认删除抄表类型「${type.name}」吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    await meterCategoryApi.delete7({ id: type.id })
    ElMessage.success('删除成功')
    fetchMeterCategories()
    resetTypeForm()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleDeleteType error:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

onMounted(async () => {
  await Promise.all([fetchBuildingList(), fetchMeterCategories(), fetchOwnerOptions()])
  fetchMeterRecordList()
})
</script>

<template>
  <div class="meter-reading-view">
    <div class="page-header">
      <div>
        <h2>抄表管理</h2>
        <p>记录水电气等表计读数，方便后续费用核算。</p>
      </div>
      <el-button type="primary" :icon="Setting" @click="openTypeDialog"> 管理抄表类型 </el-button>
    </div>

    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="所属楼栋">
          <el-select
            v-model="searchState.buildingId"
            placeholder="请选择楼栋"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in buildingOptions"
              :key="item.id"
              :label="`${item.numbers || ''}${item.units ? ` ${item.units}` : ''}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋">
          <el-select
            v-model="searchForm.houseId"
            placeholder="请选择房屋"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="item in searchHouseOptions"
              :key="item.id"
              :label="`${item.building?.numbers || ''} ${item.numbers || ''}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="抄表类型">
          <el-select
            v-model="searchForm.typeId"
            placeholder="请选择类型"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in meterCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="表计编号">
          <el-input
            v-model="searchForm.meter"
            placeholder="请输入表计编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="抄表时间">
          <el-date-picker
            v-model="searchState.currentRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item label="业主">
          <el-select
            v-model="searchForm.ownerId"
            placeholder="可按业主筛选"
            clearable
            filterable
            remote
            :remote-method="remoteSearchOwner"
            :loading="ownerLoading"
            style="width: 220px"
          >
            <el-option
              v-for="item in ownerOptions"
              :key="item.id"
              :label="ownerLabel(item)"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"> 搜索 </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-section">
      <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增抄表记录 </el-button>
      <el-button
        type="danger"
        :icon="Delete"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="抄表类型" min-width="140">
          <template #default="{ row }">{{ row.typeName || '-' }}</template>
        </el-table-column>
        <el-table-column label="房屋" min-width="160">
          <template #default="{ row }">
            <div class="cell-strong">
              {{ row.house?.building?.numbers || '-' }} {{ row.house?.numbers || '' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="业主" min-width="160">
          <template #default="{ row }">
            <div>{{ row.owner?.name || '-' }}</div>
            <div class="cell-sub" v-if="row.owner?.tel">{{ row.owner.tel }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="previousReading" label="上次读数" width="140">
          <template #default="{ row }">{{ formatNumber(row.previousReading) }}</template>
        </el-table-column>
        <el-table-column prop="currentReading" label="本次读数" width="140">
          <template #default="{ row }">{{ formatNumber(row.currentReading) }}</template>
        </el-table-column>
        <el-table-column prop="previousTime" label="上次抄表" min-width="180">
          <template #default="{ row }">{{ row.previousTime ? dayjs(row.previousTime).format('YYYY-MM-DD HH:mm') : '-' }}</template>
        </el-table-column>
        <el-table-column prop="currentTime" label="本次抄表" min-width="180">
          <template #default="{ row }">{{ row.currentTime ? dayjs(row.currentTime).format('YYYY-MM-DD HH:mm') : '-' }}</template>
        </el-table-column>
        <el-table-column prop="checkTime" label="校验时间" min-width="180">
          <template #default="{ row }">{{ row.checkTime ? dayjs(row.checkTime).format('YYYY-MM-DD HH:mm') : '-' }}</template>
        </el-table-column>
        <el-table-column prop="meter" label="表计编号" min-width="140" />
        <el-table-column prop="remarks" label="备注" min-width="220" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑抄表记录' : '新增抄表记录'"
      width="620px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="meterForm" :rules="rules" label-width="110px">
        <el-form-item label="抄表类型" prop="typeId">
          <el-select v-model="meterForm.typeId" placeholder="请选择抄表类型" filterable>
            <el-option
              v-for="item in meterCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属楼栋" prop="buildingId">
          <el-select v-model="meterForm.buildingId" placeholder="请选择楼栋" filterable>
            <el-option
              v-for="item in buildingOptions"
              :key="item.id"
              :label="`${item.numbers || ''}${item.units ? ` ${item.units}` : ''}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋" prop="houseId">
          <el-select v-model="meterForm.houseId" placeholder="请选择房屋" filterable>
            <el-option
              v-for="item in formHouseOptions"
              :key="item.id"
              :label="`${item.building?.numbers || ''} ${item.numbers || ''}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上次读数">
          <el-input v-model.number="meterForm.previousReading" type="number" placeholder="请输入上次读数" />
        </el-form-item>
        <el-form-item label="本次读数" prop="currentReading">
          <el-input v-model.number="meterForm.currentReading" type="number" placeholder="请输入本次读数" />
        </el-form-item>
        <el-form-item label="上次抄表时间">
          <el-date-picker
            v-model="meterForm.previousTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择上次抄表时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="本次抄表时间" prop="currentTime">
          <el-date-picker
            v-model="meterForm.currentTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择本次抄表时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="校验时间">
          <el-date-picker
            v-model="meterForm.checkTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择校验时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="表计编号">
          <el-input v-model="meterForm.meter" placeholder="请输入表计编号" maxlength="50" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="meterForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm(formRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="typeDialogVisible"
      title="抄表类型管理"
      width="520px"
      :close-on-click-modal="false"
    >
      <div class="type-dialog">
        <div class="type-form">
          <el-form ref="typeFormRef" :model="typeForm" :rules="typeRules" label-width="90px">
            <el-form-item label="类型名称" prop="name">
              <el-input v-model="typeForm.name" placeholder="请输入类型名称" maxlength="40" />
            </el-form-item>
            <el-form-item>
              <el-button @click="resetTypeForm">重置</el-button>
              <el-button type="primary" :loading="typeLoading" @click="submitTypeForm(typeFormRef)">
                {{ editingTypeId ? '保存修改' : '新增类型' }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="type-table">
          <el-table :data="meterCategories" border stripe height="320">
            <el-table-column prop="name" label="类型名称" min-width="200" />
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" :icon="Edit" @click="handleEditType(row)">
                  编辑
                </el-button>
                <el-button size="small" type="danger" :icon="Delete" @click="handleDeleteType(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="css" scoped>
.meter-reading-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.page-header h2 {
  margin: 0 0 6px;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.search-section,
.action-section,
.table-section,
.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.search-section {
  margin-bottom: 16px;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
  margin: 16px 0;
}

.table-section {
  margin-bottom: 16px;
}

.pagination-section {
  text-align: right;
}

.cell-strong {
  font-weight: 500;
  color: #303133;
}

.cell-sub {
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}

.type-dialog {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 16px;
}

.type-form {
  background: #f9fafc;
  padding: 16px;
  border-radius: 8px;
}

.type-table {
  border-radius: 8px;
  overflow: hidden;
}

@media (max-width: 960px) {
  .type-dialog {
    grid-template-columns: 1fr;
  }
}
</style>
